package OssAliyun;

import com.aliyun.oss.*;
import com.aliyun.oss.common.auth.CredentialsProviderFactory;
import com.aliyun.oss.common.auth.STSAssumeRoleSessionCredentialsProvider;
import com.aliyun.oss.model.GetObjectRequest;

import java.io.File;

/**
 * @author 航
 * @date 2024/05/17 11:02
 **/
public class DownloadOSS {
    private final static String endpoint = "https://oss-cn-hangzhou.aliyuncs.com";
    private final static String region = "cn-hangzhou";
    private final static String accessKeyId = "LTAI5tQnCGJCP9sf1dT8SNsk";
    private final static String accessKeySecret = "O5I4hOtBhZowjMQmcF2suUSGz18Tx2";
    // RAM角色的ARN信息
    private final static String roleArn = "acs:ram::1567362721763722:role/aliyunosstokengeneratorrole";

    public boolean downloadFile(String bucketName, String objectPath, String filePath) throws Exception{
        STSAssumeRoleSessionCredentialsProvider credentialsProvider = CredentialsProviderFactory
                .newSTSAssumeRoleSessionCredentialsProvider(region, accessKeyId, accessKeySecret, roleArn);

        OSS ossClient = new OSSClientBuilder().build(endpoint, credentialsProvider);
        // 这个方法不安全
        OSSClient ossClient1 = new OSSClient(endpoint, accessKeyId, accessKeySecret);
        try {
            // 下载Object到本地文件，并保存到指定的本地路径中。如果指定的本地文件存在会覆盖，不存在则新建。
            // 如果未指定本地路径，则下载后的文件默认保存到示例程序所属项目对应本地路径中。
            ossClient.getObject(new GetObjectRequest(bucketName, objectPath), new File(filePath));
            return true;
        } catch (OSSException oe) {
            System.out.println("Caught an OSSException, which means your request made it to OSS, "
                    + "but was rejected with an error response for some reason.");
            System.out.println("Error Message:" + oe.getErrorMessage());
            System.out.println("Error Code:" + oe.getErrorCode());
            System.out.println("Request ID:" + oe.getRequestId());
            System.out.println("Host ID:" + oe.getHostId());
            return false;
        } catch (ClientException ce) {
            System.out.println("Caught an ClientException, which means the client encountered "
                    + "a serious internal problem while trying to communicate with OSS, "
                    + "such as not being able to access the network.");
            System.out.println("Error Message:" + ce.getMessage());
            return false;
        } finally {
            if (ossClient != null) {
                ossClient.shutdown();
            }
        }
    }

}
